const ServerError = require('../common/error')

class vaildateParams {
	constructor(data, rule) {
		this.data = data
		if (rule.length <= 0) {
			this.rules = ""
		} else {
			let rulesPR = rule.split(",")
			if (rulesPR.length < 1) {
				throw new ServerError("路由规则错误", 5010)
			}
			let rules = {};
			rulesPR.map((str) => {
				let [k, v] = str.split(":")
				rules[k] = v.split("|")
			})
			let fields = Object.keys(rules)
			fields.map((field) => {
				rules[field].map(functionName => {
					this[functionName](data[field], field)
				})
			})
		}
	}
	required(val, name) {
		if (!val) {
			throw new ServerError(`${name}值是必须的`, 1101)
		}
	}
	number(val, name) {
		if (isNaN(val)) {
			throw new ServerError(`${name}值是必须是一个数字`, 1101)
		}
	}
	tel(val, name) {
		var re = /^1[3,4,5,6,7,8,9][0-9]{9}$/;
		var result = re.test(val);
		if (!result) {
			throw new ServerError(`手机号码格式不正确！`, 1101)
		}
	}
}

module.exports = vaildateParams
